<?php

namespace App\Http\Controllers;

use App\Models\CouponModel;
use App\Sevrice\ApiJwt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class CouponController extends Controller
{
    /**
     * @param Request $request
     * @return mixed
     * 查询全部优惠券信息
     */
    function couponList(Request $request)
    {
        $data = CouponModel::get()->toArray();
        return $data;
    }
    /**
     * @param Request $request
     * @return array
     * 领取优惠券
     */
    function drawCoupon(Request $request)
    {
        $arr['coupon_num'] = $request->post('id');
        $arr['user_num'] = ApiJwt::decodeToken($request->post('token'));
        $arr['created_at'] = date('YmdHis');
        $id = DB::table('sf_card_bag')->where('user_num', $arr['user_num'])->where('coupon_num', $arr['coupon_num'])->value('coupon_num');
        if ($id) {
            return ['code' => 400, 'msg' => '你已领取过了'];
        }
        $count = DB::table('sf_card_bag')->get()->count();
        if ($count >= 100) {
            return ['code' => 400, 'msg' => '你的卡券已达上限'];
        }
        $res = DB::table('sf_card_bag')->insert($arr);
        if ($res) {
            DB::table('sf_coupon_log')->insert($arr);
            CouponModel::where('coupon_id',$arr['coupon_num'])->decrement('coupon_repertory',1);
            return ['code' => 200, 'msg' => '领取成功'];
        }
        return ['code' => 400, 'msg' => '领取失败'];
    }
    function useCoupon(Request $request){
    }

    /**
     * @param Request $request
     * @return \Illuminate\Support\Collection
     * 查看我的卡券包
     */
    function myCoupon(Request $request){
        $userId= ApiJwt::decodeToken($request->post('token'));
        $data= DB::table('sf_card_bag')->join('sf_shop_coupon','coupon_num','coupon_id')->where('user_num',$userId)->get()->toArray();
        return $data;
    }

    /**
     * @param Request $request
     * @return mixed
     * 查询优惠券信息详情
     */
    function couponInfo(Request $request)
    {
        $couponBag=$request->get('bagId');
        if($couponBag){
            $couponId=DB::table('sf_card_bag')->where('cardBag_id',$couponBag)->value('coupon_num');
            $data=CouponModel::where('coupon_id',$couponId)->first();
            return  $data;
        }
    }
}
